<?php
/**
 * Order actions 
 * @desc 
 */
class CPS360_Order
{
	protected $allow_types = array('ids' , 'time' , 'uptime' , 'check') ;
	/******************Querying Interface********************/
	/**
	 * Get query results by condition
	 */
	public function order_by_ids($order_ids)
	{
		return $this->get_result('ids', $order_ids) ;
	}
	
	public function order_by_time($start_time ,$end_time ,$last_order_id)
	{
		$condition = array('start_time'=>$start_time , 'end_time'=>$end_time ,'last_order_id'=>$last_order_id);
		return $this->get_result('time', $condition) ;
	}
	
	/**
	 * get orders by update time
	 * @param string $updstart_time
	 * @param string $updend_time
	 * @param string $last_order_id
	 */
	public function order_by_updtime($updstart_time , $updend_time ,$last_order_id)
	{
		$condition = array('updstart_time'=>$updstart_time , 'updend_time'=>$updend_time , 'last_order_id'=>$last_order_id) ;
		return $this->get_result('uptime', $condition) ;
	}
	
	/**
	 * Query interface
	 * @param string $type
	 * @param mixed $params
	 */
	private function get_result($type , $params){
		if(!in_array($type, $this->allow_types)){
			return array() ;
		}
		
		$cond = array() ;
		switch ($type){
			case 'ids'://tempery solution for only numberic order id
				if(strpos(',', $params) !== false){
					$cond[] = " order_id = {$params} " ;
				}else{
					$cond[] = " order_id in ({$params}) " ;
				}
				break ;
			case 'time':
				$cond[] = " start_time > '{$params['start_time']}' " ;
				$cond[] = " end_time< '{$params['end_time']}' " ;
				break ;
			case 'uptime':
				$cond[] = " updstart_time > '{$params['updstart_time']}' " ;
				$cond[] = " updend_time < '{$params['updend_time']}' " ;
				break ;
			case 'check':
				$lastday	= date('t' , $params['bill_month']) ;
				$cond[] = " status in (3,4,5) " ;
				$start	= strtotime($params . "-01 00:00:00") ;
				$end	= strtotime($params . "-" .$lastday. " 23:59:59") ;
				$cond[]	= " start_time >= {$start} " ;
				$cond[] = " end_time <= {$end} " ;
				break ;
		}
		
		if(!empty($params['last_order_id'])){
			$cond[] = " order_id > '{$params['last_order_id']}' " ;
		}
		
		if(!empty($cond)){
			$conditions = implode(" and " , $cond);
			$where 		= " where {$conditions} " ;
		}else{
			$where		= "" ;
		}
		
		$orderby 	= " order by order_id asc limit ".CPS360_Conf::CPS_QUERY_SIZE ;
		$sql 		= "select * from " .CPS360_Conf::CPS_TABLE . $where . $orderby ;
		//db query
		$result = $db->query($sql);
		foreach ($result as $row){
			if($row['pay'] == 1){
				$status = 2 ;
			}elseif ($row['pay'] == 2){
				$status = 3 ;	
			}else{
				$status = 1 ;
			}
			$products = unserialize($row['products']);
			//format data
			$orderlist[] = 			array (
					'qid'				=> $row['qid'],													//CPS信息：360用户ID（来自跳转时传递的数据）
					'qihoo_id'			=> $row['qihoo_id'],											//CPS信息：360业务编号（来自跳转时传递的数据）
					'ext'				=> $row['ext'],													//CPS信息：360CPS扩展字段（来自跳转时传递的数据）
					'order_id'			=> $row['order_id'],											//订单Id
					'order_link'		=> 'http://'.$_SERVER['HTTP_HOST'].WEB_ROOT.'/order/index.php',	//订单页Url
					'order_time'		=> $row['create_time'],											//订单下单时间（格式：时间戳、YYYY-MM-DD HH-II-SS）
					'order_updtime'		=> $row['update_time'],											//订单最后更新时间（格式：时间戳、YYYY-MM-DD HH-II-SS）
					'server_price'		=> $row['fare'],												//订单服务费、运费、手续费等附加费用
					'coupon'			=> $row['card'],												//优惠劵、代金卷金额
					'total_price'		=> $row['origin'],												//订单总价（不含服务费用，不含优惠劵金额）
					'status'			=> $status,														//订单状态（1新订单；2已确认尚未发货和支付；3已发货；4已支付；5已完成；6已取消）
					'products'			=> $products,
					'delivery'			=> array(														//收货人信息
						'isdefault'		=> true,														//是否为默认地址
						'name'			=> $row['realname'],											//收货：姓名
						'nation'		=> '',															//收货：国家(默认:中国)
						'state'			=> '',															//收货：省份
						'city'			=> '',															//收货：市
						'district'		=> '',															//收货：区
						'address'		=> $row['address'],												//收货：详细地址
						'zip'			=> $row['zipcode'],												//收货：邮编
						'telphone'		=> null,														//收货：固定电话
						'mobile'		=> $row['mobile'],												//收货：手机
					),
				);
		}	//end foreach
		return $orderlist ;
	}
	
	/****************Checking Out Interface******************/
	/**
	 * Return check out orders
	 * @param string $billmonth
	 */
	public function check_by_month($bill_month , $last_order_id)
	{
		$condition = array('bill_month'=>$bill_month , 'last_order_id'=>$last_order_id) ;
		return $this->get_result('check', $condition) ;
	}
	
	/******************Self Using******************/
	
	/**
	 * add order to db
	 * @param mixed $assoc
	 */
	public function add_order($order_id , $assoc)
	{
		if(!$order_id) return ;
		$cpsinfo = Cps360_Api::decrypt($_COOKIE[CPS360_Conf::CPS_COOKIE_NAME]) ;
		if(!$cpsinfo) return ;
		
		//CPS信息
		$cps_order = array(
			'order_id' => $order_id,
			'qid' => $cpsinfo['qid'],
			'qihoo_id' => $cpsinfo['qihoo_id'],
			'ext' => $cpsinfo['ext'],
			'products' => serialize($assoc),
			'dateline' => time(),
		);
		//exist check
		$order_exist = $db->get(CPS360_Conf::CPS_TABLE , $order_id) ;
		if($order_exist){
			$db->update(CPS360_Conf::CPS_TABLE , $order_id , $cps_order) ;
		}else{
			$db->insert(CPS360_Conf::CPS_TABLE , $cps_order) ;
		}
		return ;
	}
	/***************End of Self Using*****************/
}